package org.jivesoftware.smack;

import java.util.Map;

import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.collections.ReferenceMap;

import com.senyint.imsdk.ISdkConfig;
import com.senyint.imsdk.SendPacketException;
import com.senyint.imsdk.util.PacketUtil;
/**
 * 
 * @author hui
 *
 */
public class ConversationManager {
    private static Map<String, Conversation> threadChats = new ReferenceMap<String, Conversation>(ReferenceMap.HARD,ReferenceMap.WEAK);

    private final Connection connection;
    private final ISdkConfig sdkCfg ;
    
    public ConversationManager(Connection conn,ISdkConfig config) {
        this.connection = conn;
        this.sdkCfg = config ;
//        PacketFilter filter = new PacketFilter() {
//            public boolean accept(Packet packet) {
//                if (!(packet instanceof Message)) {
//                    return false;
//                }
//                Message message = (Message) packet;
//                Log.d("ConversationMng","AAAAAAAAAA---->>>"+packet.toXML());
//                Message.Type messageType = message.getType();
//                boolean flag = (messageType == Message.Type.groupchat || messageType == Message.Type.chat ||  messageType == Message.Type.normal);
//            
//                if(flag || message.getConversation() != null){
//                	return true ;
//                }
//                
//                //for spark test only,
//                if(flag && message.getConversation() == null){
//                	String c = Conversation.createConversationID(message.getFromNode(),message.getTopic());
//                	if(c != null){
//                		message.setConversation(c);
//                		return true;
//                	}
//                }
//                
//                return flag ;
//            }
//        };
//        
//        // Add a listener for all message packets so that we can deliver errant
//        // messages to the best Chat instance available.
//        connection.addPacketListener(new PacketListener() {
//            public void processPacket(Packet packet) {
//                Message message = (Message) packet;
//                Log.d("ConversationMng","LLLLLLL---->>>"+packet.toXML());
//                String convs = message.getConversation();
//                Conversation chat = null ;
//                if(convs != null){
//                	chat = getConversation(convs);
//                }
//                
//                if(chat != null ){
//            		deliverMessage(chat, message);
//            	}
//            }
//        }, filter);
        
    }

    public void clearConversations() {
    	for(Conversation  c: threadChats.values()){
    		c.clearMessageListener();
    	}
    	threadChats.clear();
	}
    

    public Conversation createConversationChat(String participant, String topic, ConversationMessageListener listener) {
        Conversation chat = createConversation(participant, topic);
        if(chat == null) {
            throw new IllegalArgumentException("Conversation is null");
        }
        
        if(listener != null)
        	chat.addMessageListener(listener);
        
        return chat;
    }
    
    private Conversation createConversation(String userto,String topic) {
    	if(userto == null){
    		return null ;
    	}
    	String user = sdkCfg.getUserName();
    	String conversation = PacketUtil.createConversationID(user,userto, topic);
    	if(conversation ==null)
    		return null ;
    	if(threadChats.get(conversation) != null){
    		return threadChats.get(conversation);
    	}
    	
    	Conversation conv = new Conversation(this,sdkCfg,userto,topic);
    	threadChats.put(conversation, conv);
        return conv;
    }
    
    private Conversation getConversation(String conversation) {
    	if(threadChats.get(conversation) != null){
    		return threadChats.get(conversation);
    	}
    	return null ;
    }
    
    /**
     * 
     * @param chat	Conversation
     * @param message
     * @deprecated
     */
    @SuppressWarnings("unused")
	private void deliverMessage(Conversation chat, Message message) {
        // Here we will run any interceptors
        chat.deliver(message);
    }

    public boolean sendMessage(Conversation chat, Message message) throws SendPacketException {
        if(isAuthentificated()){
			connection.sendPacket(message);
			return true ;
		}
		throw new SendPacketException(message,"connection is not authed!");
        
    }

    public boolean isAuthentificated() {
	    if (this.connection == null)
	      return false;
	    return this.connection.isAuthenticated();
	}

    /**
     * 通知对应的会话处理接收消息
     * @param message
     */
    public void notifyConversationMessage(Message message){
    	Conversation conv = getConversation(message.getConversation());
    	if(conv != null){
    		conv.deliver(message);
    	}
    	
    }
    
}


